package io.kwdb.examples;

import io.kwdb.sdk.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class TestIlpDebug {
  public static void main(String[] args) throws Exception {
    // Test with direct HTTP client to debug
    HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

    URI writeUri = URI.create("http://127.0.0.1:9091/write");

    // Test 1: Simple ILP line
    String ilpData = "sdk_bench,host=java-debug,region=us-west usage=42.0";
    System.out.println("Sending ILP: " + ilpData);
    System.out.println("ILP bytes length: " + ilpData.getBytes(StandardCharsets.UTF_8).length);

    HttpRequest request =
        HttpRequest.newBuilder()
            .uri(writeUri)
            .timeout(Duration.ofSeconds(10))
            .header("Content-Type", "text/plain; charset=utf-8")
            .POST(HttpRequest.BodyPublishers.ofString(ilpData, StandardCharsets.UTF_8))
            .build();

    System.out.println("Request headers:");
    request.headers().map().forEach((k, v) -> System.out.println("  " + k + ": " + v));

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println("Response status: " + response.statusCode());
    System.out.println("Response body: " + response.body());
    System.out.println("Response headers:");
    response.headers().map().forEach((k, v) -> System.out.println("  " + k + ": " + v));

    // Test 2: Try without charset in Content-Type
    System.out.println("\n--- Test 2: Without charset ---");
    ilpData = "sdk_bench,host=java-debug-2,region=us-east usage=84.0";

    request =
        HttpRequest.newBuilder()
            .uri(writeUri)
            .timeout(Duration.ofSeconds(10))
            .header("Content-Type", "text/plain")
            .POST(HttpRequest.BodyPublishers.ofString(ilpData))
            .build();

    response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println("Response status: " + response.statusCode());
    System.out.println("Response body: " + response.body());

    // Test 3: Try with application/octet-stream
    System.out.println("\n--- Test 3: With application/octet-stream ---");
    ilpData = "sdk_bench,host=java-debug-3,region=eu-west usage=67.0";

    request =
        HttpRequest.newBuilder()
            .uri(writeUri)
            .timeout(Duration.ofSeconds(10))
            .header("Content-Type", "application/octet-stream")
            .POST(HttpRequest.BodyPublishers.ofString(ilpData))
            .build();

    response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println("Response status: " + response.statusCode());
    System.out.println("Response body: " + response.body());
  }
}
